/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package libase.web.jsf.bean;

import java.io.IOException;
import java.math.BigDecimal;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Iterator;
import java.util.LinkedList;
import java.util.List;
import javax.ejb.EJB;
import javax.ejb.Stateless;
import javax.inject.Named;
import javenue.csv.Csv;
import libase.entity.*;
import libase.web.DateFormat;
import nullutil.NullUtil;

/**
 *
 * @author aspr0
 */
@Named
@Stateless
public class LeaseBean extends AbstractBean
{
    private Lease l = new Lease();
    private String exportCsvMsg;
    private String exportCsvLink;
    private String exportCsvLinkText;
    @EJB
    private PreferenceBean preferenceBean;
    @EJB
    private BookBean bookBean;

    public Lease getL()
    {
        if (fetchId())
        {
            return l = em.find(Lease.class, id);
        }

        return l;
    }

    public void setL(Lease l)
    {
        this.l = l;
    }

    public List<Lease> getLeases()
    {
        return em.createNamedQuery("Lease.findAll").getResultList();
    }

    public List<Lease> getLeasesByBook()
    {
        if (fetchNamedId("bid"))
        {
            return em.createNamedQuery("Lease.findByBook").setParameter("book", new Book(nId)).getResultList();
        }
        else
        {
            return new LinkedList<Lease>();
        }
    }

    public List<Lease> getLeasesByBookCompleted()
    {
        if (fetchNamedId("bid"))
        {
            return em.createNamedQuery("Lease.findCompletedByBook").setParameter("book", new Book(nId)).getResultList();
        }
        else
        {
            return new LinkedList<Lease>();
        }
    }

    public List<Lease> getLeasesByBookUncompleted()
    {
        if (fetchNamedId("bid"))
        {
            return em.createNamedQuery("Lease.findUncompletedByBook").setParameter("book", new Book(nId)).getResultList();
        }
        else
        {
            return new LinkedList<Lease>();
        }
    }

    public void create()
    {
        l.setCompleted("N");
        l.setLeaseDt(new Date());
        em.persist(l);
        l = new Lease();
    }

    public void edit()
    {
        em.merge(l);
        l = new Lease();
    }

    public void remove()
    {
        getL();
        em.remove(l);
        l = new Lease();
    }

    public void complete()
    {
        getL();
        l.setCompleted("Y");
        l.setReturnDt(new Date());

        em.merge(l);
        l = new Lease();
    }

    /**
     * Exports leases report to csv file
     */
    public void exportCsv()
    {
        exportCsvMsg = "Unable to export. ";
        exportCsvLink = ".";

        if (fetchNamedId("bid"))
        {
            String outDir;

            try
            {
                outDir = preferenceBean.getOutputDir();
            }
            catch (PreferenceException e)
            {
                exportCsvMsg += e.getMessage();
                return;
            }
            catch (IOException e)
            {
                exportCsvMsg += e.getMessage();
                return;
            }

            List<Lease> leases = getLeasesByBook();
            Iterator<Lease> i = leases.iterator();

            Book book = new Book(new BigDecimal(0), "unknown book", new Date());
            if (fetchId())
            {
                book = bookBean.getB();
            }

            SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy.MM.dd.HH.mm.ss");
            String dateString = dateFormat.format(new Date());
            String fileName = String.format("leases.id%s.%s.csv", book.getId(), dateString);
            String filePath = outDir + fileName;
            exportCsvLink = String.format("/csv/%s", fileName);
            exportCsvLinkText = fileName;
            String titleCsv = String.format("Leases of %s captured on %s", book.toString(), dateFormat);

            Csv.Writer writerCsv = new Csv.Writer(filePath).delimiter(';');
            writerCsv
                    .value("Id")
                    .value("Lease date")
                    .value("Return date")
                    .value("Completed")
                    .newLine();

            while (i.hasNext())
            {
                Lease lease = i.next();

                writerCsv
                        .value(lease.getId().toString())
                        .value(DateFormat.asDmy(lease.getLeaseDt()))
                        .value((lease.getReturnDt() == null) ? "" : DateFormat.asDmy(lease.getReturnDt()))
                        .value(lease.getCompleted())
                        .newLine();
            }

            writerCsv.close();

            exportCsvMsg = "Export successful.";
        }
    }

    public String getExportCsvMsg()
    {
        return exportCsvMsg;
    }

    public String getExportCsvLink()
    {
        return exportCsvLink;
    }

    public String getExportCsvLinkText()
    {
        return exportCsvLinkText;
    }
}
